#include "checkermanager.h"

CheckerManager::CheckerManager(QObject *parent) :
    QObject(parent)
{


}

CheckerManager::~CheckerManager()
{

}

void CheckerManager::checkKontroller(int _cFrom, int _cTo)
{
    QJsonObject  objectLevelOne;
    dbUp();
    while ( _cFrom < _cTo )
    {
        QSqlQuery q;
        QString sq;
        sq.append( "select top 1 * from Adroit_K");
        sq.append(QString::number(_cFrom));
        sq.append(" where TimestampStr > '");
        sq.append(QDateTime::currentDateTime().addSecs(-300).toString("yyyy-MM-dd hh:mm:ss.zzz"));
        sq.append("' order by TimestampStr desc");
        ///qDebug()<<sq;
        ///2013-11-02 20:11:59.093
        q.prepare(sq);
        if ( !q.exec() )
        {
           emit myError ( q.lastError().text() );
            break;
        }
        q.first();

        if ( !q.isValid() )
            break;

        QJsonObject  objectLevelZero;
        int c = q.record().count();
        while ( c )
        {
            c--;
            objectLevelZero.insert(q.record().fieldName(c),QJsonValue::fromVariant( q.value(c) ));
        }
        objectLevelOne.insert(QString::number(_cFrom),objectLevelZero);
        _cFrom++;
    }   
    QJsonDocument d;
    qDebug()<<objectLevelOne;
    d.setObject(objectLevelOne);
    qDebug()<<d;
    emit kontrollerStatusInfo(d.toBinaryData());
    db.close();
}

void CheckerManager::dbUp()
{
    db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName("Driver={SQL SERVER};Server=192.168.0.199;Database=Adroit_DB;Trusted_Connection=yes;");
    if (!db.open()){
        emit myError (db.lastError().text() );
    }
}

